package com.amazon.shop.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 数据自动填充类
 *
 * @Author 郭非
 * @Date 2021/6/12
 * @Time 8:54
 * @Version 1.0
 */
@Component
public class CustomMetaObjectHandler implements MetaObjectHandler {
    /**
     * 插入自动填充
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        String formatDate = getFormatDate();
        //创建时间自动填充
        setFieldValByName("gmtCreated", formatDate, metaObject);
        //更新时间自动填充
        setFieldValByName("gmtModified", formatDate, metaObject);
    }

    /**
     * 更新自动填充
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        String formatDate = getFormatDate();
        //更新时间自动填充
        setFieldValByName("gmtModified", formatDate, metaObject);
    }

    /**
     * 格式化时间
     *
     * @return
     */
    private String getFormatDate() {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String formatDate = format.format(date);
        return formatDate;
    }
}
